package com.kim.product.controller;

import com.kim.product.pojo.Product;
import com.kim.product.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;


    @Value("${server.port}")
    private String port;

    //注入IP
    @Value("${spring.cloud.client.ip-address}")
    private String ip;

    //日志对象
    Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable("id") Integer id) throws InterruptedException {
        //模拟访问耗时的操作
        int i = new Random().nextInt(2);
        Thread.sleep(i*1000);
        System.out.println("time"+i*1000);
        Product product = productService.findById(id);
        //添加商品描述，用于区别
        product.setProductDesc("from "+ip+" "+port);
        return product;
    }
//    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
//    public Product findById(@PathVariable("id") Integer id) throws InterruptedException {
//        //模拟访问耗时的操作，随机时间
//        int randomNumTime = new Random().nextInt(10);
//        logger.info("randomNumTime:"+randomNumTime);
//        Thread.sleep(randomNumTime*1000);
//        Product product = productService.findById(id);
//        return product;
//    }

    @RequestMapping(value = "/",method = RequestMethod.POST)
    public String save(@RequestBody Product product){
        productService.save(product);
        return "保存成功";
    }

    @RequestMapping(value = "/",method = RequestMethod.PUT)
    public String update(@RequestBody Product product){
        productService.update(product);
        return "修改成功";
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
       productService.delete(id);
       return "删除成功";
    }

}
